package com.l2jserver.gameserver.handler.admin;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import com.l2jserver.gameserver.handler.IHandler;

/**
 * @author UnAfraid, Synerge
 */
public class AdminCommandHandler implements IHandler<IAdminCommandHandler, String>
{
	private final Map<String, IAdminCommandHandler> _datatable = new HashMap<>();
	private final Set<String> _handlerCategories = new TreeSet<>();
	
	protected AdminCommandHandler()
	{
	}
	
	@Override
	public void registerHandler(IAdminCommandHandler handler)
	{
		for (String id : handler.getAdminCommandList())
		{
			_datatable.put(id, handler);
			
			// TODO no se obtiene el nombre del package
			// Synerge - Agregamos tambien el handler en la categoria que corresponda
			// final String packageName = handler.getClass().getPackage().getName();
			// _handlerCategories.add(packageName.substring(packageName.lastIndexOf(".") + 1));
		}
	}
	
	@Override
	public synchronized void removeHandler(IAdminCommandHandler handler)
	{
		for (String id : handler.getAdminCommandList())
		{
			_datatable.remove(id);
		}
	}
	
	@Override
	public IAdminCommandHandler getHandler(String adminCommand)
	{
		String command = adminCommand;
		if (adminCommand.contains(" "))
		{
			command = adminCommand.substring(0, adminCommand.indexOf(" "));
		}
		return _datatable.get(command);
	}
	
	public Map<String, IAdminCommandHandler> getHandlers()
	{
		return _datatable;
	}
	
	public Set<String> getHandlerCategories()
	{
		return _handlerCategories;
	}
	
	@Override
	public int size()
	{
		return _datatable.size();
	}
	
	public static AdminCommandHandler getInstance()
	{
		return SingletonHolder._instance;
	}
	
	private static class SingletonHolder
	{
		protected static final AdminCommandHandler _instance = new AdminCommandHandler();
	}
}
